<template>
  <div class="edit-card">
    <div class="card-header">
      <h1 class="card-title">编辑博客文章</h1>
      <div class="row">
        <span>发布日期:</span>
        <input type="datetime-local" class="date-input" v-model="blog.created_at" />
      </div>
    </div>

    <div class="row" style="margin-top: 20px">
      <div style="flex: 0.5">
        <div class="row">
          <span>文章标题</span>
          <NewInput
            placeholder="输入文章标题..."
            :value="blog.title"
            @updateValue="
              (v) => {
                blog.title = v
              }
            " />
        </div>
      </div>
      <div style="flex: 0.5">
        <div class="row">
          <span>文章标签</span>
          <div style="flex: 1">
            <div class="tags-dropdown">
              <div class="tags-selector" @click="showDropmenu = !showDropmenu">
                <div v-if="blog.labels && blog.labels.length !== 0" class="tags-container">
                  <TagChip
                    v-for="(label, index) in blog.labels"
                    :index="index"
                    :label="label"
                    @removeTag="removeLabelFromBlogLabels(index)" />
                </div>
                <p v-else style="color: gray">选择或创建标签</p>
                <i class="fas fa-chevron-down"></i>
              </div>
              <div v-if="showDropmenu" class="dropdown-menu">
                <div class="dropdown-item" @click="showDialog = true">
                  <i
                    class="fas fa-plus-circle"
                    style="color: var(--primary); margin-right: 5px"></i>
                  <span>创建新标签</span>
                </div>
                <div
                  v-for="(label, index) in allLabels"
                  class="dropdown-item"
                  :key="index"
                  @click="addLabelToBlogLabels(label.name)">
                  {{ label.name }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="row">
      <span>文章内容</span>
    </div>
    <MdEditor
      v-model="blog.context"
      catalogLayout="flat"
      class="blog-content"
      @on-get-catalog="
        (h) => {
          headList = h
        }
      " />

    <div class="row">
      <span>文章描述</span>
      <NewInput
        mode="textarea"
        placeholder="输入文章简要描述, 用于封面展示，50字左右，可根据文章内容使用ai生成"
        :value="blog.desc"
        @updateValue="
          (v) => {
            blog.desc = v
          }
        " />
      <Button
        text="ai生成"
        @click-it="
          switchTipStatus({
            level: 'warning',
            msg: 'ai生成 功能暂未开放~',
          })
        "></Button>
    </div>
    <div class="row" style="justify-content: space-between">
      <div class="row" style="position: relative">
        <span>博客封面</span>
        <Button text="上传图片" @click-it="fileInputRef.click()"></Button>
        <input
          type="file"
          accept="image/*"
          @change="onCoverChange"
          ref="fileInputRef"
          style="display: none" />
        <img
          v-if="blog.blog_cover"
          :src="blog.blog_cover"
          alt="封面预览"
          style="max-width: 80px; max-height: 80px; border-radius: 8px; border: 1px solid #eee" />
        <!-- <a style="font-size: 14px">删除</a> -->
      </div>
      <div class="row">
        <span>置顶</span>
        <input
          type="checkbox"
          v-model="blog.is_top"
          style="width: 20px; height: 20px; accent-color: var(--primary); border-radius: 50%" />
      </div>
    </div>

    <div v-if="!isBlogLoading" class="footer-buttons">
      <Button text="取消" @click-it="emits('cancel')"></Button>
      <Button text="保存文章" @click-it="saveBlog"></Button>
    </div>
    <SmallLoading v-else fix-height="50px" loading-text="正在保存, 请稍等..."></SmallLoading>
  </div>
  <DialogCard v-if="showDialog" dialog-title="创建标签">
    <template v-slot:body>
      <div class="row">
        <span>标签名称</span>
        <NewInput
          placeholder="输入新标签名称..."
          :value="labelName"
          @update-value="
            (v) => {
              labelName = v
            }
          " />
      </div>
    </template>
    <template v-slot:footer>
      <Button text="取消" @click-it="cancelAddLabelToAllLabels"></Button>
      <Button text="创建" @click-it="addLabelToAllLabels"></Button>
    </template>
  </DialogCard>
  <DialogCard v-if="showCoverDialog" dialog-title="封面预览">
    <template v-slot:body>
      <img
        :src="tempCover"
        alt="封面预览"
        style="max-width: 200px; max-height: 200px; border-radius: 8px" />
    </template>
    <template v-slot:footer>
      <Button text="取消" @click-it="cancelCover"></Button>
      <Button text="重新上传" @click-it="reuploadCover"></Button>
      <Button text="确认" @click-it="confirmCover"></Button>
    </template>
  </DialogCard>
</template>

<script setup>
import { MdEditor } from "md-editor-v3"
import { onMounted, ref } from "vue"
import { generateTOC } from "@/utils/toc"
import { AddTag, GetTagsAll } from "@/apis/allAPI/tag"
import appStore from "@/stores"
import Button from "@/components/Button.vue"
import "md-editor-v3/lib/style.css"
import TagChip from "./TagChip.vue"
import NewInput from "./NewInput.vue"
import DialogCard from "./Dialog.vue"
import SmallLoading from "./SmallLoading.vue"
import { storeToRefs } from "pinia"

const { switchTipStatus } = appStore.homeviewStore
const { isBlogLoading } = storeToRefs(appStore.homeviewStore)
const { blog } = defineProps({
  blog: Object,
})
const emits = defineEmits(["save", "cancel"])
const showDropmenu = ref(false)
const showDialog = ref(false)
const headList = ref(null)
const isValid = () => {
  if (blog.title === "") {
    return "博客标题不能为空！"
  } else if (blog.context === "") {
    return "博客内容不能为空！"
  } else if (blog.desc === "") {
    return "博客描述不能为空！"
  } else {
    return ""
  }
}

const saveBlog = () => {
  const msg = isValid()
  if (msg === "") {
    // 筛选
    isBlogLoading.value = true
    blog.toc = generateTOC(headList.value)
    blog.updated_at = blog.created_at
    emits("save")
  } else {
    switchTipStatus({
      level: "warning",
      msg: msg,
    })
  }
}

const allLabels = ref([])

const addLabelToBlogLabels = (label) => {
  if (blog.labels.includes(label)) {
    switchTipStatus({ level: "warning", msg: `${label} 已添加` })
  } else {
    blog.labels.push(label)
  }
  showDropmenu.value = false
}
const removeLabelFromBlogLabels = (index) => {
  blog.labels.splice(index, 1)
}

const labelName = ref("")
const cancelAddLabelToAllLabels = () => {
  showDialog.value = false
  labelName.value = ""
}
const addLabelToAllLabels = () => {
  var names = []
  Object.values(allLabels.value).forEach((element) => {
    names.push(element.name)
  })
  if (names.includes(labelName.value)) {
    switchTipStatus({ level: "warning", msg: `${labelName.value} 已添加！` })
  } else {
    AddTag(
      { name: labelName.value },
      (rData) => {
        allLabels.value = rData
        cancelAddLabelToAllLabels()
      },
      cancelAddLabelToAllLabels()
    )
  }
}

const showCoverDialog = ref(false)
const tempCover = ref("")
const fileInputRef = ref(null)

const onCoverChange = (e) => {
  const file = e.target.files[0]
  if (!file) return
  const reader = new FileReader()
  reader.onload = (ev) => {
    tempCover.value = ev.target.result
    showCoverDialog.value = true
  }
  reader.readAsDataURL(file)
}

const cancelCover = () => {
  showCoverDialog.value = false
  tempCover.value = ""
  if (fileInputRef.value) fileInputRef.value.value = ""
}

const reuploadCover = () => {
  if (fileInputRef.value) fileInputRef.value.click()
}

const confirmCover = () => {
  blog.blog_cover = tempCover.value
  showCoverDialog.value = false
}

onMounted(() => {
  GetTagsAll((rData) => {
    allLabels.value = rData
  })
})
</script>

<style scoped>
@import "/src/assets/styles/allStyles/previewTheme.css";
.edit-card {
  background: var(--card-bg);
  backdrop-filter: blur(14px);
  -webkit-backdrop-filter: blur(14px);
  border-radius: var(--border-radius);
  border: 1px solid var(--glass-border);
  box-shadow: var(--shadow);
  overflow: hidden;
  margin: 30px;
  padding: 30px;
  transition: var(--transition);
}

.edit-card:hover {
  transform: translateY(-5px);
  box-shadow: var(--shadow);
  border-color: rgba(var(--primary-rgb), 0.5);
}

.card-header {
  display: flex;
  justify-content: space-between;
  border-bottom: 1px solid var(--glass-border);
}

.card-title {
  font-size: 1.8rem;
  font-weight: 700;
  color: var(--primary);
}

.card-title::after {
  content: var(--title-gift);
  margin-left: 10px;
}

.row {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  gap: 15px;
}

.row span {
  font-weight: 500;
  color: var(--primary);
  font-size: 1.1rem;
}

/* 标签区域 */
.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

/* 标签下拉菜单 */
.tags-dropdown {
  position: relative;
  flex: 1;
}

.tags-selector {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 12px;
  border-radius: var(--border-radius);
  border: 2px solid var(--glass-border);
  background: rgba(var(--bg-darker-rgb), 0.1);
  transition: var(--transition);
}

.tags-selector:hover {
  border-color: var(--primary);
}

.tags-selector i {
  margin-left: auto;
  color: var(--gray);
  transition: transform 0.3s ease;
}

.tags-selector.active i {
  transform: rotate(180deg);
}

.dropdown-menu {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: var(--card-bg);
  border-radius: 12px;
  border: 1px solid var(--glass-border);
  box-shadow: var(--shadow);
  max-height: 300px;
  overflow-y: auto;
  z-index: 100;
  margin-top: 5px;
  transition: var(--transition);
}

.dropdown-item {
  padding: 12px 18px;
  cursor: pointer;
  transition: var(--transition);
}

.dropdown-item:hover {
  background: rgba(var(--primary-rgb), 0.1);
  color: var(--primary);
}

.create-tag {
  display: flex;
  align-items: center;
  padding: 12px 18px;
  color: var(--primary);
}

.create-tag i {
  margin-right: 10px;
}

/* 日期选择器 */
.date-input {
  flex: 1;
  padding: 12px;
  border-radius: var(--border-radius);
  border: 2px solid var(--glass-border);
  background: rgba(var(--bg-darker-rgb), 0.5);
  color: var(--text);
  transition: var(--transition);
}

.date-input:focus {
  outline: none;
  border-color: var(--primary);
  box-shadow: 0 0 0 3px rgba(var(--primary-rgb), 0.2);
}

/* Markdown编辑器区域 */
.blog-content {
  background: var(--card-bg);
  border-radius: var(--border-radius);
  padding: 20px;
  margin-bottom: 40px;
  box-shadow: var(--shadow);
  border: 1px solid var(--glass-border);
  transition: var(--transition);
  word-wrap: break-word;
  overflow-wrap: break-word;
}

/* 底部按钮 */
.footer-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 15px;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid var(--glass-border);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .edit-container {
    padding: 10px;
  }

  .edit-card {
    padding: 20px;
  }

  .card-header {
    flex-direction: column;
    align-items: center;
    gap: 15px;
  }
}

@media (max-width: 480px) {
  .row {
    flex-direction: column;
    align-items: center;
    gap: 15px;
  }
}
</style>
